package com.alks.function.service.impl.produce;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.UserInfoUtil;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.beanutils.StringUtils;
import com.alks.entity.data.entity.PcDrawDetail;
import com.alks.entity.data.entity.PcDrawTemp2;
import com.alks.entity.data.entity.PcLotHead;
import com.alks.entity.data.entity.PcStitchBarcodeHead;
import com.alks.entity.data.enums.chengkong.DefineEnum;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.PcLotHeadCountDto;
import com.alks.function.data.dto.chengKong.produce.LotNoDetailDto;
import com.alks.function.data.dto.chengKong.produce.PcLotDetailDto;
import com.alks.function.data.dto.produce.PcDrawDetailDto;
import com.alks.function.data.dto.produce.PcDrawTemp2Dto;
import com.alks.function.data.dto.produce.PcLotUsageToPcDrawDetailDto;
import com.alks.function.data.dto.produce.PcStitchBarcodeHeadListDto;
import com.alks.function.data.request.chengKong.LotNoRequest;
import com.alks.function.data.request.produce.*;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.produce.PcStitchBarcodeHeadMapper;
import com.alks.function.service.produce.PcStitchBarcodeHeadService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PcStitchBarcodeHeadServiceImpl implements PcStitchBarcodeHeadService {

    @Resource
    private PcStitchBarcodeHeadMapper pcStitchBarcodeHeadMapper;

    @Override
    @AutoPageAop
    public ResponseInfo PcStitchBarcodeHeadList(PcStitchBarcodeHeadListRequest request) {
        Map map = new HashMap<>();
        request.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
        List<PcStitchBarcodeHeadListDto> pcStitchBarcodeHeadList = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadList(request);
        PcLotHeadCountDto headCount = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadCount(request);
        Integer caseQtyCount = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadCaseQtyCount(request);
        PcLotHeadCountDto OutINQtyCount = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadListTotalQuantityofReceivedReceivedMaterials(request);
        PageInfo pageInfo = new PageInfo(pcStitchBarcodeHeadList);
        map.put("list", pcStitchBarcodeHeadList);
        map.put("total", pageInfo.getTotal());
        map.put("inSumCount", (headCount == null) ? 0 : headCount.getOrderCount());
        map.put("outSumCount", (headCount == null) ? 0 : headCount.getSurplusCount());
        map.put("caseQtyCount", (caseQtyCount == null) ? 0 : caseQtyCount);
        map.put("inQtyCount", (OutINQtyCount == null) ? 0 : OutINQtyCount.getSunInQty());
        map.put("OutQtyCount", (OutINQtyCount == null) ? 0 : ( OutINQtyCount.getSunOutQty() == null) ? 0 : OutINQtyCount.getSunOutQty());
        return ResponseInfo.ok(map);
    }

    @Resource
    private PcLotHeadMapper pcLotHeadMapper;

    /**
     * 生成鞋面标签
     * @param request
     * @return
     */
    @Override
    public ResponseInfo GenerateShoeUpperLabels(PcStitchBarcodeHeadAddRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())) {
            return ResponseInfo.error("请输入指令!");
        }
        if (request.getCaseTty() == null || request.getCaseTty().compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseInfo.error("请输入每袋双数!");
        }

        int minBagQty = 1;
        int maxBagQty = 500;
        if (request.getCaseTty().intValue() > maxBagQty || request.getCaseTty().intValue() < minBagQty) {
            return ResponseInfo.error(StringUtils.format("袋装数量有效的范围{}~{}", new Object[]{Integer.valueOf(minBagQty), Integer.valueOf(maxBagQty)}));
        }

        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        LambdaQueryWrapper<PcLotHead> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PcLotHead::getLotNo, request.getLotNo()).eq(PcLotHead::getCompanyId, companyId);
        PcLotHead head = pcLotHeadMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(head)){
            return ResponseInfo.error("指令不存在,请核实!");
        }
        if (!"Y".equals(head.getCheckFlag())){
            return ResponseInfo.error("指令未审核!");
        }
        int lsNo = request.getLsNo();
        if (lsNo==0) {
            Integer exist = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadExist2(request.getLotNo(), companyId,1);
            if (exist != null && exist == 0) {
                return ResponseInfo.error(StringUtils.format("指令{}未生成正单鞋面标签,请先生成正单鞋面标签!", new Object[]{request.getLotNo()}));
            }
            Integer pcStitchBarcodeHeadExist = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadExist2(request.getLotNo(), companyId,0);
            if (pcStitchBarcodeHeadExist != null && pcStitchBarcodeHeadExist > 0) {
                return ResponseInfo.error(StringUtils.format("指令{}已生成预补鞋面标签,请核实!", new Object[]{request.getLotNo()}));
            }
        }else {
            Integer pcStitchBarcodeHeadExist = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadExist2(request.getLotNo(), companyId,1);
            if (pcStitchBarcodeHeadExist != null && pcStitchBarcodeHeadExist > 0) {
                return ResponseInfo.error(StringUtils.format("指令{}已生成正单鞋面标签,请核实!", new Object[]{request.getLotNo()}));
            }
        }

        List<PcLotDetailDto> codeDetails = pcLotHeadMapper.getCodeDetails(request.getLotNo(), companyId);

        if (ObjectUtils.isEmpty(codeDetails)) {
            throw new ServiceErrorException(StringUtils.format("指令{}未找到鞋码信息,请核实!", new Object[]{request.getLotNo()}));
        }
        List<PcStitchBarcodeHead> list = new ArrayList<>();
        for (PcLotDetailDto codeDetail : codeDetails) {
            BigDecimal orderQty=BigDecimal.ZERO;
            int maxSeqNo=0;
            if (lsNo==1){
                orderQty=codeDetail.getOrderQtyCount();
            }else {
                orderQty=codeDetail.getSurplusQtyCount();
                maxSeqNo = pcStitchBarcodeHeadMapper.pcStitchBarcodeHeadMapper(request.getLotNo(), companyId, codeDetail.getSizeNo());

            }
            if (orderQty != null && orderQty.compareTo(BigDecimal.ZERO) > 0) {
                //除了多少次
                BigDecimal quotient = orderQty.divide(request.getCaseTty(), 0, RoundingMode.DOWN);
                //还剩多少数
                BigDecimal remainder = orderQty.remainder(request.getCaseTty());
                //所有次数
                BigDecimal order = BigDecimal.ZERO;
                //如果有余数加1
                if (remainder != null && remainder.compareTo(BigDecimal.ZERO) > 0) {
                    order = quotient.add(BigDecimal.ONE);
                } else {
                    //否则就是除数
                    order = quotient;
                }
                PcStitchBarcodeHead entity = null;
                if (quotient != null && quotient.compareTo(BigDecimal.ZERO) > 0) {
                    for (int i = 0; i < quotient.intValue(); i++) {
                        //根据除次,生成订单号、指令、序号、每带双数、序号生成条码
                        if (lsNo==1) {
                            entity = getPcStitchBarcodeHead(request.getLotNo(), companyId, codeDetail, i + 1, request.getCaseTty(), String.format("%04d", i + 1),request.getLsNo());
                        }else {
                            entity = getPcStitchBarcodeHead(request.getLotNo(), companyId, codeDetail, maxSeqNo+i + 1, request.getCaseTty(), String.format("%04d", maxSeqNo+i + 1),request.getLsNo());
                        }
                        list.add(entity);
                    }
                    if (remainder != null && remainder.compareTo(BigDecimal.ZERO) > 0) {
                        //根据除次+1设置订单号、指令、序号、每带双数、序号生成条码
                        if (lsNo==1) {
                            entity = getPcStitchBarcodeHead(request.getLotNo(), companyId, codeDetail, order.intValue(), remainder, String.format("%04d", quotient.intValue() + 1),request.getLsNo());
                        }else {
                            entity = getPcStitchBarcodeHead(request.getLotNo(), companyId, codeDetail,maxSeqNo+ order.intValue(), remainder, String.format("%04d", maxSeqNo+quotient.intValue() + 1),request.getLsNo());
                        }
                        list.add(entity);
                    }
                } else {
                    //如果除次等于0
                    if (remainder != null && remainder.compareTo(BigDecimal.ZERO) > 0) {
                        if (lsNo==1) {
                            entity = getPcStitchBarcodeHead(request.getLotNo(), companyId, codeDetail, order.intValue(), remainder, String.format("%04d", order.intValue()),request.getLsNo());
                        }else {
                            entity = getPcStitchBarcodeHead(request.getLotNo(), companyId, codeDetail,maxSeqNo+ order.intValue(), remainder, String.format("%04d", maxSeqNo+order.intValue()),request.getLsNo());
                        }
                        list.add(entity);
                    }
                }
            }
        }
        if (!ObjectUtils.isEmpty(list)) {
            int batchSize = 800;
            if (list.size() > batchSize) {
                int totalSize = list.size();
                int batchCount = (totalSize + batchSize - 1) / batchSize;
                for (int i = 0; i < batchCount; i++) {
                    int start = i * batchSize;
                    int end = Math.min(start + batchSize, totalSize);
                    List<PcStitchBarcodeHead> batchList = list.subList(start, end);
                    pcStitchBarcodeHeadMapper.addPcStitchBarcodeHead(batchList);
                }
            } else {
                pcStitchBarcodeHeadMapper.addPcStitchBarcodeHead(list);
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 重新生成鞋面标签
     * @param lists
     * @param lotNo
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo regenerate(List<PcStitchBarcodeHeadAddRequest> lists, String lotNo) {
        if (ObjectUtils.isEmpty(lists)){
            return ResponseInfo.error("未选择任何号码记录!");
        }
        int lsNo = lists.get(0).getLsNo();
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        LambdaQueryWrapper<PcLotHead> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PcLotHead::getLotNo, lotNo).eq(PcLotHead::getCompanyId, companyId);
        PcLotHead head = pcLotHeadMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(head)){
            return ResponseInfo.error("指令不存在!");
        }
        List<PcStitchBarcodeHead> datas = new ArrayList();
        List<PcStitchBarcodeHead> list = pcStitchBarcodeHeadMapper.selectUnStartBarcode(companyId,lotNo,lsNo);

        Map<String, List<PcStitchBarcodeHead>> sizeNo2BarCode = new LinkedHashMap();

        for (PcStitchBarcodeHead sbh : list) {
            List<PcStitchBarcodeHead> subList = sizeNo2BarCode.computeIfAbsent(sbh.getSizeNo(), k -> new ArrayList<>());
            subList.add(sbh);
        }

        List<String>  barcodeList= new ArrayList();
        Iterator<PcStitchBarcodeHeadAddRequest> var17 = lists.iterator();
        while(var17.hasNext()) {
            PcStitchBarcodeHeadAddRequest t = var17.next();
            String sizeNo = t.getSizeNo();
            List<PcStitchBarcodeHead> removeList = sizeNo2BarCode.get(sizeNo);
            if (ObjectUtils.isEmpty(removeList)){
                throw new ServiceErrorException(StringUtils.format("号码【{}】的鞋面标签已全部采集或者已全部入库,请核实", new Object[]{sizeNo}));
            }
            int caseQty = t.getCaseTty()!=null? t.getCaseTty().intValue():0;
            if (caseQty <= 0) {
                throw new ServiceErrorException(StringUtils.format("号码【{}】未设置每袋双数!", new Object[]{sizeNo}));
            }
            int maxSeqNo = pcStitchBarcodeHeadMapper.pcStitchBarcodeHeadMapper(lotNo, companyId, sizeNo);
            ++maxSeqNo;

            int orderQty = 0;
            int sizeSeq = 0;

            for (PcStitchBarcodeHead t1 : removeList) {
                barcodeList.add(t1.getBarcode());
                if (t1.getSizeSeq()!=null){
                    sizeSeq=t1.getSizeSeq();
                }
                orderQty += t1.getCaseQty();
            }

            while(orderQty > 0) {
                PcStitchBarcodeHead stitchBarcodeHead = new PcStitchBarcodeHead();
                stitchBarcodeHead.setCompanyId(companyId);
                stitchBarcodeHead.setLotNo(lotNo);
                stitchBarcodeHead.setLsNo(lsNo);
                stitchBarcodeHead.setSizeNo(sizeNo);
                stitchBarcodeHead.setSeqNo(maxSeqNo);
                int realQty = caseQty;
                if (orderQty < caseQty) {
                    realQty = orderQty;
                }

                orderQty -= caseQty;
                stitchBarcodeHead.setCaseQty(realQty);
                stitchBarcodeHead.setSizeSeq(sizeSeq);
                stitchBarcodeHead.setBarcode(StringUtils.format("{}{}{}A", new Object[]{lotNo, sizeNo, String.format("%04d", maxSeqNo)}));
                ++maxSeqNo;
                datas.add(stitchBarcodeHead);
            }
        }

        int batchSize = 800;
        if (!ObjectUtils.isEmpty(datas)) {
            if (datas.size() > batchSize) {
                int totalSize = datas.size();
                int batchCount = (totalSize + batchSize - 1) / batchSize;
                for (int i = 0; i < batchCount; i++) {
                    int start = i * batchSize;
                    int end = Math.min(start + batchSize, totalSize);
                    List<PcStitchBarcodeHead> batchList = datas.subList(start, end);
                    pcStitchBarcodeHeadMapper.addPcStitchBarcodeHead(batchList);
                }
            } else {
                pcStitchBarcodeHeadMapper.addPcStitchBarcodeHead(datas);
            }
        }

        if (!ObjectUtils.isEmpty(barcodeList)){
            if (barcodeList.size() > batchSize){
                int totalSize = barcodeList.size();
                int batchCount = (totalSize + batchSize - 1) / batchSize;
                for (int i = 0; i < batchCount; i++) {
                    int start = i * batchSize;
                    int end = Math.min(start + batchSize, totalSize);
                    List<String> batchList = barcodeList.subList(start, end);
                    pcStitchBarcodeHeadMapper.deleteBarcodes(batchList,companyId);
                }
            }else {
                pcStitchBarcodeHeadMapper.deleteBarcodes(barcodeList,companyId);
            }
        }

        int time = pcStitchBarcodeHeadMapper.countNoEqual(lotNo, companyId);
        if (time > 0){
            throw new ServiceErrorException("鞋面标签重新生成异常-订单数据与标签总数不符合!");
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 校验标签是否已经入库
     * @param barcode
     * @return
     */
    @Override
    public ResponseInfo checkLabel(String barcode) {
        String companyId = UserIdThread.get().getCompanyId();
        PcStitchBarcodeHead head = pcStitchBarcodeHeadMapper.checkCheckLabelByBarcode(barcode, companyId);
        if (ObjectUtils.isEmpty(head)){
            return ResponseInfo.error("标签已采集或者已入库,请核实");
        }
        return ResponseInfo.ok(head);
    }

    /**
     * 分割标签
     * @param caseQtys
     * @param barcode
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo splitLabel(List<Integer> caseQtys, String barcode) {
        if (ObjectUtils.isEmpty(caseQtys)){
            return ResponseInfo.error("未设置任何标签!");
        }
        if (caseQtys.size() <= 1) {
            return ResponseInfo.error("拆分标签数必须大于1!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        PcStitchBarcodeHead head = pcStitchBarcodeHeadMapper.checkCheckLabelByBarcode(barcode, companyId);
        if (ObjectUtils.isEmpty(head)){
            return ResponseInfo.error("鞋面标签已扫描或者已入库,无法执行拆分");
        }
        int caseQty = head.getCaseQty();
        int realQty = 0;
        for (Integer qty : caseQtys) {
            if (qty <= 0) {
                throw new ServiceErrorException("子标签双数必须大于0!");
            }
            realQty += qty;
        }
        if (realQty != caseQty) {
            throw new ServiceErrorException("子标签的总双数与被拆分的标签双数不符,请核实!");
        }

        //对标签数量做排序
        caseQtys.sort(new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });

        int maxSeqNo = pcStitchBarcodeHeadMapper.pcStitchBarcodeHeadMapper( head.getLotNo(),head.getCompanyId(), head.getSizeNo());
        ++maxSeqNo;
        List<PcStitchBarcodeHead> datas = new ArrayList();
        for (Integer qty : caseQtys) {
            PcStitchBarcodeHead stitchBarcodeHead = new PcStitchBarcodeHead();
            stitchBarcodeHead.setCompanyId(head.getCompanyId());
            stitchBarcodeHead.setLotNo(head.getLotNo());
            stitchBarcodeHead.setLsNo(head.getLsNo());
            stitchBarcodeHead.setSizeNo(head.getSizeNo());
            stitchBarcodeHead.setSeqNo(maxSeqNo);
            stitchBarcodeHead.setCaseQty(qty);
            stitchBarcodeHead.setSizeSeq(head.getSizeSeq());
            stitchBarcodeHead.setBarcode(StringUtils.format("{}{}{}B", new Object[]{head.getLotNo(), head.getSizeNo(), String.format("%04d", maxSeqNo)}));
            ++maxSeqNo;
            datas.add(stitchBarcodeHead);
        }
        int total = pcStitchBarcodeHeadMapper.addPcStitchBarcodeHead(datas);
        int deleteSize = pcStitchBarcodeHeadMapper.deleteBarcode(companyId, barcode);
        if (total == 0) {
            throw new ServiceErrorException("拆分标签失败 - 新增子标签失败!");
        }else if (deleteSize == 0) {
            throw new ServiceErrorException("拆分标签失败 - 删除标签失败!");
        }else{
            int count = pcStitchBarcodeHeadMapper.countNoEqual(head.getLotNo(), companyId);
            if (count > 0) {
                throw new ServiceErrorException("拆分鞋面标签异常-订单数据与标签总数不符合!");
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 重新生成标签号码集合
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo regenerateSizeNoList(String lotNo) {
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        LambdaQueryWrapper<PcLotHead> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PcLotHead::getLotNo, lotNo).eq(PcLotHead::getCompanyId, companyId);
        PcLotHead head = pcLotHeadMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(head)){
            return ResponseInfo.error("指令不存在!");
        }
        List<Map<String, Object>> list = pcStitchBarcodeHeadMapper.selectRegenerateSize(lotNo, companyId);
        if (ObjectUtils.isEmpty(list)){
            return ResponseInfo.error(StringUtils.format("指令{}所有标签已采集或者已入库，请核实", new Object[] { head.getLotNo() }));
        }
        return ResponseInfo.ok(list);
    }

    /**
     * 重新生成标签
     * @param barcode
     * @return
     */
    @Override
    public ResponseInfo reprint(String barcode) {
        String companyId = UserIdThread.get().getCompanyId();
        PcStitchBarcodeHead sbh = pcStitchBarcodeHeadMapper.selectByBarcode(barcode, companyId);
        if (ObjectUtils.isEmpty(sbh)){
            return ResponseInfo.error("该标签信息不存在!");
        }
        if (!"Y".equals(sbh.getPrintFlag())){
            return ResponseInfo.error("该标签未打印过,无法重新生成标签!");
        }
        //判断是否扫描入库
        Integer count = pcStitchBarcodeHeadMapper.queryCollectStitchByBarcode(barcode, companyId);
        if (count != null && count > 0) {
            return ResponseInfo.error("鞋面存在已采集或者已入库,无法重新生成标签!");
        }
        int maxSeqNo = pcStitchBarcodeHeadMapper.pcStitchBarcodeHeadMapper( sbh.getLotNo(),sbh.getCompanyId(), sbh.getSizeNo());
        ++maxSeqNo;
        sbh.setBarcode(StringUtils.format("{}{}{}C", new Object[]{sbh.getLotNo(), sbh.getSizeNo(), String.format("%04d", maxSeqNo)}));
        sbh.setRePrintFlag("Y");
        sbh.setPrintTime(LocalDateTime.now());
        sbh.setSeqNo(maxSeqNo);
        sbh.setPrintFlag(null);
        int result = pcStitchBarcodeHeadMapper.updateRePrintFlagByBarcode(sbh, barcode);
        if (result != 1) {
            throw new ServiceErrorException("重打标签失败,请核实！");
        } else {
            return ResponseInfo.ok(sbh);
        }
    }

    /**
     * 鞋面标签通用方法
     * @param lotNo 指令
     * @param companyId 公司
     * @param codeDetail 码详情
     * @param seqNo 设置序号
     * @param caseQty 每袋双数
     * @param YB 生成条形码
     * @return
     */
    @NotNull
    private PcStitchBarcodeHead getPcStitchBarcodeHead(String lotNo, String companyId, PcLotDetailDto codeDetail, int seqNo, BigDecimal caseQty, String YB,int lsNo) {
        PcStitchBarcodeHead entity = new PcStitchBarcodeHead();
        entity.setLotNo(lotNo);
        entity.setCompanyId(companyId);
        entity.setLsNo(lsNo);
        entity.setSizeNo(codeDetail.getSizeNo());
        entity.setSeqNo(seqNo);
        entity.setCaseQty(caseQty.intValue());
        String barcode = lotNo + codeDetail.getSizeNo() + YB;
        entity.setBarcode(barcode);
        entity.setSizeSeq(Integer.valueOf(codeDetail.getSeqNo()));
        return entity;
    }

    /**
     * 删除
     * @param lotNo
     * @return
     */
    @Override
    public ResponseInfo delete(String lotNo) {
        String companyId = UserInfoUtil.getUserInfo().getCompanyId();
        LambdaQueryWrapper<PcLotHead> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PcLotHead::getLotNo, lotNo).eq(PcLotHead::getCompanyId, companyId);
        PcLotHead head = pcLotHeadMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(head)){
            return ResponseInfo.error("指令不存在,请核实!");
        }
        //判断是否扫描入库
        Integer count = pcStitchBarcodeHeadMapper.queryCollectStitchByLotNo(lotNo, companyId);
        if (count != null && count > 0) {
            return ResponseInfo.error("鞋面存在已采集或者已入库,无法删除!");
        }
        pcStitchBarcodeHeadMapper.delete(lotNo,companyId);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 打印所选标签
     * @param request
     * @return
     */
    @Override
    public ResponseInfo PrintSelectedLabels(PrintSelectedLabelsRequest request) {
        if (ObjectUtils.isEmpty(request.getBarcodeList())){
            return ResponseInfo.error("请选择记录!");
        }
        if (ObjectUtils.isEmpty(request.getDeptName())){
            return ResponseInfo.error("请选择部门!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        pcStitchBarcodeHeadMapper.updatePcStitchBarcodeHead(request.getBarcodeList(),request.getDeptName(),request.getDeptNo(), LocalDateTime.now(), DefineEnum.CHECKOUT_FLAG.getValue(),companyId);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 打印鞋面标签
     * @param request
     * @return
     */
    @Override
    public ResponseInfo PrintShoeUpperLabels(PrintSelectedLabelsRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("请选择指令!");
        }
        if (ObjectUtils.isEmpty(request.getDeptName())){
            return ResponseInfo.error("请选择部门!");
        }
        if (ObjectUtils.isEmpty(request.getBarcodeList())){
            return ResponseInfo.error("请选择记录!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        Integer queryCount = pcLotHeadMapper.queryCount(request.getLotNo(), companyId);
        if (queryCount == null || queryCount <= 0) {
            return ResponseInfo.error("请输入正确的指令!");
        }
        Integer pcStitchBarcodeHeadExist = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadExist(request.getLotNo(), companyId);
        if (pcStitchBarcodeHeadExist == null || pcStitchBarcodeHeadExist<=0) {
            return ResponseInfo.error("该指令没有标签记录!");
        }
        List<String> barcodeList = pcStitchBarcodeHeadMapper.getPcStitchBarcodeHeadList2(request.getLotNo(),request.getBarcodeList(),companyId);
        if (!ObjectUtils.isEmpty(barcodeList)){
            pcStitchBarcodeHeadMapper.updatePcStitchBarcodeHead(barcodeList,request.getDeptName(),request.getDeptNo(), LocalDateTime.now(), DefineEnum.CHECKOUT_FLAG.getValue(), companyId);
        }
        List<PcStitchBarcodeHeadListDto> list = pcStitchBarcodeHeadMapper.printPcStitchBarcodeHeadList(request.getLotNo(), request.getBarcodeList(), companyId);
        return ResponseInfo.ok(list);
    }

    /**
     * 显示号码
     * @param request
     * @return
     */
    @Override
    public ResponseInfo DisplayNumber(LotNoRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        LotNoDetailDto lotNoDetail = pcLotHeadMapper.getLotNoDetail(request.getLotNo(),companyId);
        return ResponseInfo.ok(lotNoDetail);
    }

    /**
     * 选择材料-指令用量查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo QueryOfInstructionUsageDetails(LotNoQueryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        if (!ObjectUtils.isEmpty(request.getLotNo())) {
            Integer count = pcStitchBarcodeHeadMapper.getPcCostLot(request.getLotNo(), companyId);
            if (count != null && count > 0) {
                return ResponseInfo.error(request.getLotNo() + "指令已结束!");
            }
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        PageRecord<PcLotUsageToPcDrawDetailDto> list = new PageRecord<>();
        List<PcLotUsageToPcDrawDetailDto> detailList = pcStitchBarcodeHeadMapper.QueryOfInstructionUsageDetails(request);
        PageInfo pageInfo=new PageInfo(detailList);
        list.setTotal(pageInfo.getTotal());
        list.setList(detailList);
        return ResponseInfo.ok(list);
    }

    /**
     * 指令用量明细-待确认料批处理查询
     * @return
     * @param choose
     */
    @Override
    public ResponseInfo QueryOfInstructionUsageDetails2(Integer choose) {
        if (ObjectUtils.isEmpty(choose)){
            return ResponseInfo.error("请选择操作!");
        }
        //获取领料类型
        String slipType = getSlipType(choose);
        String loginName = UserIdThread.get().getLoginName();
        String companyId = UserIdThread.get().getCompanyId();
        List<PcDrawTemp2Dto> query = pcStitchBarcodeHeadMapper.QueryOfInstructionUsageDetails2(loginName,slipType,companyId);
        Map map = new HashMap();
        map.put("list",query);
        map.put("total",query.size());
        BigDecimal count=BigDecimal.ZERO;
        if (!ObjectUtils.isEmpty(query)){
            for (PcDrawTemp2Dto t : query) {
                if (t.getTtlUsage()!=null){
                    count=count.add(t.getTtlUsage());
                }
            }
        }
        map.put("count",count);
        return ResponseInfo.ok(map);
    }

    /**
     * 领料明细档查询
     * @param request
     * @param choose
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo MaterialRequisitionDetailsFile(PcDrawDetailRequest request, Integer choose) {
        if (ObjectUtils.isEmpty(choose)){
            return ResponseInfo.error("请选择操作!");
        }
        //获取领料类型
        String slipType = getSlipType(choose);
        PageRecord<PcDrawDetailDto> list = new PageRecord<>();
        String loginName = UserIdThread.get().getLoginName();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<PcDrawDetailDto> detailList = pcStitchBarcodeHeadMapper.MaterialRequisitionDetailsFile(request,loginName,slipType);
        PageInfo pageInfo=new PageInfo(detailList);
        list.setTotal(pageInfo.getTotal());
        list.setList(detailList);
        return ResponseInfo.ok(list);
    }

    /**
     * 待领批处理
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo PendingBatchProcessing(List<PcDrawTemp2Request> request, Integer choose) {
        if (ObjectUtils.isEmpty(request)){
            return ResponseInfo.error("请选择记录!");
        }
        if (ObjectUtils.isEmpty(choose)){
            return ResponseInfo.error("请选择操作!");
        }
        //获取领料类型
        String slipType = getSlipType(choose);
        for (PcDrawTemp2Request t : request) {
            if ("1".equals(t.getStatus())){
                return ResponseInfo.error("存在已生成领料单号的记录!");
            }
        }
        List<PcDrawDetailAddRequest> filteredList =new ArrayList<>();

        List<PcDrawTemp2> list = request.stream().map(t -> {
            if ("0".equals(t.getStatus())){
                PcDrawDetailAddRequest addRequest = new PcDrawDetailAddRequest();
                BeanUtil.copyProperties(t,addRequest);
                filteredList.add(addRequest);
            }
            PcDrawTemp2 entity = new PcDrawTemp2();
            BeanUtil.copyProperties(t, entity);
            entity.setSysDate(LocalDateTime.now());
            UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
            entity.setSysUser(userInfo.getLoginName());
            entity.setCompanyId(userInfo.getCompanyId());
            entity.setSlipType(slipType);
            return entity;
        }).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(filteredList)){
            pcStitchBarcodeHeadMapper.delPcDrawTemp2(filteredList,slipType);
        }
        if (!ObjectUtils.isEmpty(list)){
            pcStitchBarcodeHeadMapper.addPcDrawTemp2(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 获取领料类型
     * @param choose
     */
    private String getSlipType(Integer choose) {
        String slipType = "";
        switch (choose) {
            case 0:
                slipType = "指令领料";
                break;
            case 1:
                slipType = "预加领料";
                break;
            case 2:
                slipType = "补料领料";
                break;
            case 3:
                slipType = "多购领料";
                break;
            default:
                slipType = null;
                break;
        }
        return slipType;
    }

    @Resource
    private RedisService redisService;

    /**
     * 领料批处理
     * @param request
     * @param choose
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo BatchProcessingOfMaterialRequisition(List<PcDrawDetailAddRequest> request, Integer choose) {
        if (ObjectUtils.isEmpty(request)){
            return ResponseInfo.error("待批处理数据为空!");
        }
        if (ObjectUtils.isEmpty(choose)){
            return ResponseInfo.error("请选择操作!");
        }
        //获取领料类型
        String slipType = getSlipType(choose);
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        List<PcDrawTemp2Dto> query = pcStitchBarcodeHeadMapper.QueryOfInstructionUsageDetails2(userInfo.getLoginName(),slipType,userInfo.getCompanyId());
        if (ObjectUtils.isEmpty(query)){
            return ResponseInfo.error("待批处理数据为空或已经生成领料单,不可重复请求处理!");
        }
        String slipNo = redisService.slipNoGenerate("BFL", 4, 2);
        List<PcDrawDetail> list = query.stream().map(t -> {
            PcDrawDetail entity = new PcDrawDetail();
            BeanUtil.copyProperties(t, entity);
            entity.setDeptNo(request.get(0).getDeptNo());
            entity.setDeptName(request.get(0).getDeptName());
            entity.setSlipDate(request.get(0).getSlipDate());
            entity.setStockNo("X1");
            entity.setSlipNo(slipNo);
            entity.setSysDate(LocalDateTime.now());
            entity.setSysUser(userInfo.getLoginName());
            entity.setCompanyId(userInfo.getCompanyId());
            entity.setSlipType(slipType);
            return entity;
        }).collect(Collectors.toList());
        pcStitchBarcodeHeadMapper.delPcDrawTemp2(request,slipType);
        if (!ObjectUtils.isEmpty(list)){
            pcStitchBarcodeHeadMapper.addPcDrawDetail(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 打印领料单
     * @param request
     * @return
     */
    @Override
    public ResponseInfo PrintMaterialRequisitionForm(List<PcDrawDetailUpdateRequest> request) {
        if (ObjectUtils.isEmpty(request)){
            return ResponseInfo.error("请选择记录!");
        }
        int lotNoCount=0;
        int slipNoCount=0;
        int mtlNoCount=0;
        for (PcDrawDetailUpdateRequest t : request) {
            if (ObjectUtils.isEmpty(t.getLotNo())){
                lotNoCount++;
            }
            if (ObjectUtils.isEmpty(t.getSlipNo())){
                slipNoCount++;
            }
            if (ObjectUtils.isEmpty(t.getMtlNo())){
                mtlNoCount++;
            }
            if (t.getPrintTime()!=null){
                t.setPrintTime(t.getPrintTime().add(BigDecimal.ONE));
            }
            if (t.getPrintTime()==null){
                t.setPrintTime(BigDecimal.ONE);
            }
        }
        if (lotNoCount>0){
            return ResponseInfo.error("指令不能为空!");
        }
        if (slipNoCount>0){
            return ResponseInfo.error("领料单号不能为空!");
        }
        if (mtlNoCount>0){
            return ResponseInfo.error("物料编码不能为空!");
        }
        pcStitchBarcodeHeadMapper.updatePcDrawDetailByPrintTime(request,"Y",LocalDateTime.now());
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 指令领料修改备注
     * @param request
     * @param choose
     * @return
     */
    @Override
    public ResponseInfo ModifyRemarks(PcDrawDetailUpdateRequest request, Integer choose) {
        if (ObjectUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("指令不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getMtlNo())){
            return ResponseInfo.error("物料编码不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getSlipNo())){
            return ResponseInfo.error("备注不能为空!");
        }
        if (ObjectUtils.isEmpty(choose)){
            return ResponseInfo.error("请选择操作!");
        }
        //获取领料类型
        String slipType = getSlipType(choose);
        //修改slipNo是备注
        pcStitchBarcodeHeadMapper.updatePcDrawTemp2(request.getLotNo(),request.getMtlNo(),request.getSlipNo(),slipType);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 部位用量明细查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo partNameList(PcDrawDetailUpdateRequest request) {
        return ResponseInfo.ok(pcStitchBarcodeHeadMapper.getPartNameList(request.getLotNo(),request.getMtlNo()));
    }

    /**
     * 选择预加材料查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo SelectPreAddedMaterials(LotNoQueryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        if (!ObjectUtils.isEmpty(request.getLotNo())) {
            Integer count = pcStitchBarcodeHeadMapper.getPcCostLot(request.getLotNo(), companyId);
            if (count != null && count > 0) {
                return ResponseInfo.error(request.getLotNo() + "指令已结束!");
            }
        }
        PageRecord<PcLotUsageToPcDrawDetailDto> list = new PageRecord<>();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<PcLotUsageToPcDrawDetailDto> detailList = pcStitchBarcodeHeadMapper.SelectPreAddedMaterials(request);
        PageInfo pageInfo=new PageInfo(detailList);
        list.setTotal(pageInfo.getTotal());
        list.setList(detailList);
        return ResponseInfo.ok(list);
    }

    /**
     * 选择材料-补单领料查询
     * @param request
     * @return
     */
    @AutoPageAop
    @Override
    public ResponseInfo SelectSupplementaryOrderMaterials(LotNoQueryRequest request) {
        PageRecord<PcLotUsageToPcDrawDetailDto> list = new PageRecord<>();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<PcLotUsageToPcDrawDetailDto> detailList = pcStitchBarcodeHeadMapper.SelectSupplementaryOrderMaterials(request);
        PageInfo pageInfo=new PageInfo(detailList);
        list.setTotal(pageInfo.getTotal());
        list.setList(detailList);
        return ResponseInfo.ok(list);
    }

    /**
     * 打印单据
     * @param request
     * @return
     */
    @Override
    public ResponseInfo PrintDocuments(PcDrawDetailUpdateRequest request) {
        if (ObjectUtils.isEmpty(request.getSlipNo())){
            return ResponseInfo.error("领料单号不能为空!");
        }
        BigDecimal printTime = request.getPrintTime();
        if (printTime==null){
            printTime=BigDecimal.ONE;
        }else {
            printTime=printTime.add(BigDecimal.ONE);
        }
        pcStitchBarcodeHeadMapper.updatePcDrawDetailByPrintTime2(request.getSlipNo(),printTime,"Y",LocalDateTime.now());
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 多购查询
     * @param request
     * @return
     */
    @Override
    public ResponseInfo moreList(LotNoQueryRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        request.setCompanyId(companyId);
        if (!ObjectUtils.isEmpty(request.getLotNo())) {
            Integer count = pcStitchBarcodeHeadMapper.getPcCostLot(request.getLotNo(), companyId);
            if (count != null && count > 0) {
                return ResponseInfo.error(request.getLotNo() + "指令已结束!");
            }
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        PageRecord<PcLotUsageToPcDrawDetailDto> list = new PageRecord<>();
        List<PcLotUsageToPcDrawDetailDto> detailList = pcStitchBarcodeHeadMapper.moreList(request);
        PageInfo pageInfo=new PageInfo(detailList);
        list.setTotal(pageInfo.getTotal());
        list.setList(detailList);
        return ResponseInfo.ok(list);
    }

    /**
     * 多购领料
     * @param request
     * @return
     */
    @Override
    public ResponseInfo moreCollar(List<PcDrawDetailAddRequest> request) {
        if (ObjectUtils.isEmpty(request)){
            return ResponseInfo.error("请选择记录!");
        }
        //获取领料类型
        String slipType = getSlipType(3);
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        String slipNo = redisService.slipNoGenerate("BFL", 4, 2);
        List<PcDrawDetail> list = request.stream().map(t -> {
            PcDrawDetail entity = new PcDrawDetail();
            BeanUtil.copyProperties(t, entity);
            entity.setDeptNo(request.get(0).getDeptNo());
            entity.setDeptName(request.get(0).getDeptName());
            entity.setSlipDate(request.get(0).getSlipDate());
            entity.setStockNo("X1");
            entity.setSlipNo(slipNo);
            entity.setSysDate(LocalDateTime.now());
            entity.setSysUser(userInfo.getLoginName());
            entity.setCompanyId(userInfo.getCompanyId());
            entity.setSlipType(slipType);
            return entity;
        }).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(list)){
            pcStitchBarcodeHeadMapper.addPcDrawDetail(list);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 多购领料前处理
     * @param request
     * @return
     */
    @Override
    public ResponseInfo moreCheck(PcDrawDetailAddRequest request) {
        if (ObjectUtils.isEmpty(request.getLotNo())){
            return ResponseInfo.error("指令不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getMtlNo())){
            return ResponseInfo.error("物料编码不能为空!");
        }
        if (ObjectUtils.isEmpty(request.getReqQty())){
            return ResponseInfo.error("请领量不能为空!");
        }
        String companyId = UserIdThread.get().getCompanyId();
        PcLotUsageToPcDrawDetailDto dto = pcStitchBarcodeHeadMapper.moreList2(request,companyId);
        if (dto==null){
            return ResponseInfo.error("无多购数据!");
        }
        if (dto.getNotActQty().compareTo(request.getReqQty())<0){
            return ResponseInfo.error("请领料超过可申请领料数");
        }
        return ResponseInfo.ok();
    }

    /**
     * 领料明细档
     * @param request
     * @return
     */
    @Override
    public ResponseInfo moreList2(PcDrawDetailRequest request) {
        //获取领料类型
        String slipType = getSlipType(3);
        PageRecord<PcDrawDetailDto> list = new PageRecord<>();
        String loginName = UserIdThread.get().getLoginName();
        request.setCompanyId(UserIdThread.get().getCompanyId());
        List<PcDrawDetailDto> detailList = pcStitchBarcodeHeadMapper.moreList3(request,loginName,slipType);
        PageInfo pageInfo=new PageInfo(detailList);
        list.setTotal(pageInfo.getTotal());
        list.setList(detailList);
        return ResponseInfo.ok(list);
    }
}
